import { isEmptyObj, deepCopy } from '@/utils/tools'

// 本地数据缓存
interface account{

    signTime: string,
    index:number,
    [propname:string]: any

}

interface accounts{

    [userAccount:string]: account
   
}

interface state {

    accounts:accounts,
    max:number,
    accountsFilteCache: any
    
}

class localStore {

    state:state = {

        // 根据登录账号缓存数据
        accounts: {},

        // 最大缓存数
        max: 5 ,

        // 缓存过滤结果
        accountsFilteCache: {}

    }

    mutations = {  

        refreshAccounts(){

        }

    }

    getters = {

        // 账户列表
        accountsList(state){

            let accounts = state['accounts']
            let cache = [];

            Object.keys(accounts).forEach(key =>{

                let item = accounts[key];
                cache[item.index] = { account: key, username: item.username };
                
            })
            
            cache.sort(() => 1)

            return cache;
        }   
        
    }   
    
    actions = {
        

        initSet({state, commit, dispatch}, data){

            // 账号
            state['accounts'] = take('accounts') || {}

        },
        
        
        // 添加缓存账号
        addAccounts({state, commit, dispatch}, data:accounts){

            dispatch('accountsFilte', data).then(({existent, nonExistent}) =>{

                // 隐式更新state属性, 保证对象被刷新
                Object.assign(state.accounts, nonExistent);
                state.accounts = deepCopy(state.accounts);


                if(!isEmptyObj(existent)){
                    console.error(`缓存账号已存在: ${Object.keys(existent)}`)
                }

                save('accounts', state.accounts)
                
            });
            

        },

        // 更新缓存账号数据
        updateAccounts({state, commit, dispatch}, data:accounts){

            dispatch('accountsFilte', data).then(({existent, nonExistent}) =>{

                
                // 隐式更新state属性, 保证对象被刷新 (注: 更新数据时，不要覆盖原index值)
                Object.keys(existent).forEach(key =>{
                    Object.assign(state.accounts[key], existent[key])
                })
                
                state.accounts = deepCopy(state.accounts);
            
                if(!isEmptyObj(nonExistent)){
                    console.error(`缓存账号不存在: ${Object.keys(nonExistent)}`)
                }

                save('accounts', state.accounts)
                
            })
            
          
        },

        // 拆分数据
        accountsFilte({state, commit, dispatch}, data:accounts){

            let {cacheData, cacheFilte} = state.accountsFilteCache;

            if(JSON.stringify(cacheData) === JSON.stringify(data)){
                return cacheFilte;
            }
            
            let accounts = state.accounts;
            let accountsKey = Object.keys(accounts);
            let dataKey = Object.keys(data);
            let accountsSet = new Set(accountsKey);
            let accountsLen = Object.keys(state.accounts).length;
            let initNum = Object.keys(state.accounts).length - 1; 
            
            
            let existent = {};
            let nonExistent = {};

            // 分类筛选
            dataKey.forEach(key =>{

              let pushObj =  accountsSet.has(key) ? existent : nonExistent;
              Object.assign(pushObj, {[key]: data[key]})
            
            })

            // 添加编号
            nonExistent = setIndex(initNum, nonExistent);
            
            let end = {existent, nonExistent}

            // 缓存计算结果
            state.accountsFilteCache = { cacheData: data, cacheFilte: end }

            return end
        },


        has({state, commit, dispatch}, data:accounts){

            return dispatch('accountsFilte', data).then(({existent, nonExistent}) =>{

                return !isEmptyObj(existent);

            })

        },
        
    }
    
}

// 本地保存
function save(key:string, data:any):boolean{

    try {
        localStorage.setItem(key, JSON.stringify(data));
        return true
    } catch(error) {
        console.error(`本地缓存保存失败: ${error}`)
        return false
    }
    
}

// 提取本地数据
function take(key:string):any{

    let data;

    try {
        data = JSON.parse(localStorage.getItem(key));
    } catch(error) {
        console.error(`本地缓存取出失败: ${error}`)
    }
 
    return data
}

// 移除本地数据
function remove(key:string){
    localStorage.removeItem(key)
}

// 添加编号
function setIndex(initNum, data){
   
   Object.keys(data).forEach(key =>{
       
       initNum++;

       data[key]['index'] = initNum

   })

   return data;
    
}

export default localStore